package com.token.iot.bratterycharging.gateway.server;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.outstanding.framework.base.OutstandingService;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.core.TransactionContext;
import com.outstanding.framework.utils.NetUtils;
import com.token.iot.bratterycharging.gateway.Code;
import com.token.iot.bratterycharging.gateway.CodeType;
import com.token.iot.bratterycharging.gateway.IDGeneration;
import com.token.iot.bratterycharging.gateway.IMEI;
import com.token.iot.bratterycharging.gateway.Oper;
import com.token.iot.bratterycharging.gateway.Sender;
import com.token.iot.bratterycharging.gateway.api.Constant;
import com.token.iot.bratterycharging.gateway.dao.CodeHistoryDAO;
import com.token.iot.bratterycharging.gateway.utils.ChannelHandlerContextUtil;

import io.netty.channel.ChannelHandlerContext;

@Service
public class OperService extends OutstandingService {

	@Autowired
	private CodeHistoryDAO dao;

	public int process(Oper oper, byte[] b, ChannelHandlerContext ctx) throws PendingException {
		String imei = IMEI.getIMEIEnableNull(ctx);
		String sessionid = IDGeneration.getSessionID(b);
		try {
			//调用响应指令
			return oper.onCall(b, ctx);
		} finally {
			try {
				String ip = ChannelHandlerContextUtil.getIP(ctx);
				Code code = new Code();
				code.setCode(oper.getCode());
				code.setCodeType(CodeType.Oper);
				String strParams = new String(b);
				code.setParams(strParams);
				code.setImei(imei);
				code.setIp(ip);
				String serverIp = NetUtils.getLocalIP();
				code.setServerIp(serverIp);
				code.setDeviceType(Constant.DEVICETYPE);
				code.setSessionId(sessionid);
				dao.insert(code);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

}
